/**
 * 动态引入组件
 */

import React from 'react'
import Loading from '@/components/loading'
import { isFunction } from 'loadsh'

export const asyncComponent = (loadComponent) =>
  class AsyncComponent extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        loading: true,
        Component: null
      }
    }

    componentDidMount() {
      this.mounted = true
      const importComponent = isFunction(loadComponent) ? loadComponent() : loadComponent
      importComponent.then((cmp) => {
        if (this.mounted) {
          this.setState({
            loading: false,
            Component: cmp.default
          })
        }
      })
    }

    componentWillUnmount() {
      this.mounted = false
    }

    render() {
      const { loading, Component } = this.state
      return !loading && <Component {...this.props} />
    }
  }
